
package my.OrderMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.GetChars;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class OrderMessage extends Activity {
    /** Called when the activity is first created. */

	EditText msg_text;
	Button msg_send;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        DbGetData dbGetData = new DbGetData();
        String phoneNumber;
        phoneNumber = getMyPhoneNumber();
        
        msg_text = (EditText)findViewById(R.id.msg_text);
        msg_send = (Button)findViewById(R.id.msg_send);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("hpNum", phoneNumber));
		String selectDb = dbGetData.dbGetData("http://118.32.182.248:8080/JSON_JSP_SERVER/OrderMessage/R_ID_SELECT_01.jsp", params);
		
		try {
			JSONObject json = new JSONObject(selectDb);
			selectDb = json.getString("result");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
		// 핸폰번호에 핸폰 고유ID 발급이 안되어 있음 발급 신청 화면 Call
		if (selectDb.equals("0")) {
			phoneRegistration();
			Log.e("test","text111");
			finish();
		}
        
        // 보내기 보튼 클릭시 
        msg_send.setOnClickListener(new OnClickListener() {
			
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					try {
						// 메시지를 보낼때 sender(발급받은 ID, 토큰인증값(개발자 Gmail로 인증받은 토큰값), 태울메시지)
//						sender(C2DMReceiver.registration_id, "DQAAAKMAAAD1tn6vNT1xH1mB3lmPisqN7jxGE-ElVu3c-3V1u_pntcB_-8Q7s285vFn59fixAO-verGDTajuWe4sgO8kxNMdecRobFNrOX6bV2c6eMrHFRfiXndt4EyJkvcoEJzrUzE6gAGPYEfG-GFQ4FV4mzG81XwZpXZn6naUuXjWF18HksFtrxl7JbMqgR6_YEiuAy8B9GbBDJHkGxsKvtsj_y0B0megSHSOorIEpyIgCVEoog", msg_text.getText().toString());
						sender("APA91bEt4SJlH14hVEsrweZQf4s3jBRHJTN5YKw-FahGibDLSgWUCtjlQaK8fUZfHJGU8v0N8WTsI83NFjvIMecioJAcOq1VaX30HHoRFVx8MFesLvF6tvE", "DQAAAKMAAAD1tn6vNT1xH1mB3lmPisqN7jxGE-ElVu3c-3V1u_pntcB_-8Q7s285vFn59fixAO-verGDTajuWe4sgO8kxNMdecRobFNrOX6bV2c6eMrHFRfiXndt4EyJkvcoEJzrUzE6gAGPYEfG-GFQ4FV4mzG81XwZpXZn6naUuXjWF18HksFtrxl7JbMqgR6_YEiuAy8B9GbBDJHkGxsKvtsj_y0B0megSHSOorIEpyIgCVEoog", msg_text.getText().toString());
//						Toast.makeText(getApplicationContext(), C2DMReceiver.registration_id, Toast.LENGTH_SHORT).show();
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
    }
    
    //메세지 보냄
    public void sender(String regId,String authToken,String msg) throws Exception{
    	StringBuffer postDataBuilder = new StringBuffer();
        
    	postDataBuilder.append("registration_id="+regId); //등록ID
    	postDataBuilder.append("&collapse_key=1"); 
    	postDataBuilder.append("&delay_while_idle=1");
    	postDataBuilder.append("&data.msg="+URLEncoder.encode(msg, "UTF-8")); //태울 메시지

        byte[] postData = postDataBuilder.toString().getBytes("UTF8");

        URL url = new URL("https://android.apis.google.com/c2dm/send");
        
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);

        OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();

        conn.getInputStream();
    }
    
    // 개발자 고유 토큰값 가져오기
    public String getAuthToken() throws Exception{
    	String authtoken = "";
        
    	StringBuffer postDataBuilder = new StringBuffer();
        postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); //똑같이 써주셔야 합니다.
        postDataBuilder.append("&Email=ayukawa7777@gmail.com");  //개발자 구글 id
        postDataBuilder.append("&Passwd=madoka77");	          //개발자 구글 비빌번호
        postDataBuilder.append("&service=ac2dm");						
        postDataBuilder.append("&source=test-1.0");

        byte[] postData = postDataBuilder.toString().getBytes("UTF8");

        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postData.length));

        
        OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        
        String sidLine = br.readLine();
        String lsidLine = br.readLine();
        String authLine = br.readLine();
        
        System.out.println("sidLine----------->>>"+sidLine);
        System.out.println("lsidLine----------->>>"+lsidLine);
        System.out.println("authLine----------->>>"+authLine);
        System.out.println("AuthKey----------->>>"+authLine.substring(5, authLine.length()));

        authtoken = authLine.substring(5, authLine.length());
        
     return authtoken;
    }
    
    // 어플 실행된 핸드폰번호 가져오기 
    public String getMyPhoneNumber(){
    	TelephonyManager mTelephonyMgr;  
    	mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
    	return mTelephonyMgr.getLine1Number();
    }
    
    public void phoneRegistration() {
		Intent introIntent= new Intent(getApplicationContext(), PhoneRegistration.class);
		startActivity(introIntent);
		
    }
}
